package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.hjq.http.listener.HttpCallback;
import com.hjq.umeng.UmengClient;
import com.qiantu.api.entity.LoginBean;
import com.qiantu.api.entity.SmsBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.aop.SingleClick;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.AppConfig;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.utils.PhoneUUIDUtils;
import com.qiantu.phone.widget.CursorFrameTextView;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class CaptchaActivity extends AppActivity {

    private static final String INTENT_KEY_IN_PHONE = "phone";
    private static final String INTENT_KEY_IN_SMS_ID = "smsId";

    @Log
    public static void start(Context context, String phone, String smsType, String smsId) {
        Intent intent = new Intent(context, CaptchaActivity.class);
        intent.putExtra(INTENT_KEY_IN_PHONE, phone);
        intent.putExtra("smsType", smsType);
        intent.putExtra(INTENT_KEY_IN_SMS_ID, smsId);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    private EditText editSmsCode;
    private CursorFrameTextView tvSmsCode1;
    private CursorFrameTextView tvSmsCode2;
    private CursorFrameTextView tvSmsCode3;
    private CursorFrameTextView tvSmsCode4;
    private TextView tvCountDown;
    private View loadingView;
    private CursorFrameTextView.OnPasteCallback mOnPasteCallback;
    private Handler mHandler;
    private String phone;
    private String smsId;
    private String smsType;
    private int countDownTime = 60;

    @Override
    protected int getLayoutId() {
        return R.layout.captcha_activity;
    }

    @Override
    protected void initView() {
        UmengClient.init(AppApplication.getInstance(), AppConfig.isLogEnable());
        phone = getIntent().getStringExtra(INTENT_KEY_IN_PHONE);
        smsId = getIntent().getStringExtra(INTENT_KEY_IN_SMS_ID);
        smsType = getIntent().getStringExtra("smsType");
        TextView tvPhone = findViewById(R.id.tv_phone);
        tvPhone.setText(phone);
        editSmsCode = findViewById(R.id.edit_sms_code);
        tvSmsCode1 = findViewById(R.id.tv_sms_code_1);
        tvSmsCode2 = findViewById(R.id.tv_sms_code_2);
        tvSmsCode3 = findViewById(R.id.tv_sms_code_3);
        tvSmsCode4 = findViewById(R.id.tv_sms_code_4);
        tvCountDown = findViewById(R.id.tv_count_down);
        loadingView = findViewById(R.id.loading_view);
        setOnClickListener(tvSmsCode1, tvSmsCode2, tvSmsCode3, tvSmsCode4, tvCountDown);
        initCodeView();
        if(mHandler == null){
            mHandler = new Handler();
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                showTvSmsCodeSoftInput();
            }
        }, 200);
        startCountDown();
    }

    private void startCountDown(){
        countDownTime = 60;
        mHandler.post(countDownRunnable);
    }

    private Runnable countDownRunnable = new Runnable() {
        @Override
        public void run() {
            countDownTime--;
            tvCountDown.setText(countDownTime + getString(R.string.get_again_count_down));
            tvCountDown.setTextColor(AppApplication.getInstance().getThemeColor(R.attr.textColor2));
            tvCountDown.setEnabled(false);
            if(countDownTime == 0){
                tvCountDown.setText(R.string.get_again);
                tvCountDown.setTextColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
                tvCountDown.setEnabled(true);
                return;
            }
            mHandler.postDelayed(countDownRunnable, 996);
        }
    };

    private void initCodeView(){
        editSmsCode.setText(null);
        tvSmsCode1.setSelected(true);
        if (mOnPasteCallback == null) {
            mOnPasteCallback = new CursorFrameTextView.OnPasteCallback() {
                @Override
                public void onPaste(String data) {
                    if (data == null){
                        return;
                    }
                    if (data.length()>4){
                        data = data.substring(0, 4);
                    }
                    editSmsCode.setText(data);
                    editSmsCode.setSelection(data.length());
                }
            };
        }
        tvSmsCode1.setOnPasteCallback(mOnPasteCallback);
        tvSmsCode2.setOnPasteCallback(mOnPasteCallback);
        tvSmsCode3.setOnPasteCallback(mOnPasteCallback);
        tvSmsCode4.setOnPasteCallback(mOnPasteCallback);
        editSmsCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                for (int i = 0; i < 4; i++) {
                    int currentLength = s.length();
                    String s1 = i < currentLength ? String.valueOf(s.charAt(i)) : "";
                    switch (i) {
                        case 0:
                            tvSmsCode1.setText(s1);
                            if (currentLength >= i) {
                                tvSmsCode1.setSelected(true);
                            } else {
                                tvSmsCode1.setSelected(false);
                            }
                            break;
                        case 1:
                            tvSmsCode2.setText(s1);
                            if (currentLength >= i) {
                                tvSmsCode2.setSelected(true);
                            } else {
                                tvSmsCode2.setSelected(false);
                            }
                            break;
                        case 2:
                            tvSmsCode3.setText(s1);
                            if (currentLength >= i) {
                                tvSmsCode3.setSelected(true);
                            } else {
                                tvSmsCode3.setSelected(false);
                            }
                            break;
                        case 3:
                            tvSmsCode4.setText(s1);
                            if (currentLength >= i) {
                                tvSmsCode4.setSelected(true);
                            } else {
                                tvSmsCode4.setSelected(false);
                            }
                            break;
                    }
                }
                if (s.length() == 4) {
                    if ("login".equals(smsType)){
                        login(s.toString());
                    }
                }
            }
        });
        editSmsCode.setText(null);
    }

    @Override
    protected void initData() {
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_sms_code_1:
            case R.id.tv_sms_code_2:
            case R.id.tv_sms_code_3:
            case R.id.tv_sms_code_4:
                showTvSmsCodeSoftInput();
                break;
            case R.id.tv_count_down:
                getCode();
                break;
        }
    }

    private void login(String code){
        String androidId = PhoneUUIDUtils.getDeviceUUID(AppApplication.getInstance());
        LLHttpManager.applogin(this, phone, code, smsId, androidId, AppApplication.getInstance().pushDeviceId, new HttpCallback<HttpData<LoginBean>>(this){
            @Override
            public void onStart(Call call) {
                loadingView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onSucceed(HttpData<LoginBean> result) {
                super.onSucceed(result);
                AppApplication.getInstance().setCurLoginInfo(phone, result.getData());
                editSmsCode.clearFocus();
                hideKeyboard(editSmsCode);
                switch (result.getData().getRegistrationProgress()){
                    case 1:
                        InfoSupplementActivity.start(CaptchaActivity.this);
                        //关闭所有页面
                        ActivityManager.getInstance().finishAllActivities();
                        break;
                    case 2:
                        if(result.getData().isOwnHouse()){//已拥有房屋
                            AppApplication.getInstance().changeHouseData(CaptchaActivity.this, true, getString(R.string.init_house_info));
                        }else{
                            FamilyInfoActivity.start(CaptchaActivity.this);
                            //关闭所有页面
                            ActivityManager.getInstance().finishAllActivities();
                        }
                        break;
                    case 3:
                        AppApplication.getInstance().changeHouseData(CaptchaActivity.this, true, getString(R.string.init_house_info));
                        break;
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
                editSmsCode.setText(null);
                loadingView.setVisibility(View.GONE);
            }
        });
    }

    private void getCode(){
        Map<String, Object> data = new HashMap<>();
        data.put("mobile", phone);
        data.put("smsType", smsType);
        LLHttpManager.sendSms(this, data, new HttpCallback<HttpData<SmsBean>>(this){
            @Override
            public void onStart(Call call) {
                showDialog();
            }

            @Override
            public void onSucceed(HttpData<SmsBean> data) {
                if(data.isRequestSucceed()){
                    toast(R.string.sms_code_send);
                    smsId = data.getData().getSmsID();
                    //开始倒计时
                    startCountDown();
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }


            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    private void showTvSmsCodeSoftInput() {
        editSmsCode.requestFocus();
        showKeyboard(editSmsCode);
    }

    public void safeHideKeyboard(MotionEvent event, View view) {
        try {
            if (view != null && view instanceof EditText) {
                int[] location = {0, 0};
                view.getLocationInWindow(location);
                int left = location[0], top = location[1], right = left
                        + view.getWidth(), bootom = top + view.getHeight();
                int[] location1 = {0, 0};
                tvSmsCode1.getLocationInWindow(location1);
                int[] location2 = {0, 0};
                tvSmsCode2.getLocationInWindow(location2);
                int[] location3 = {0, 0};
                tvSmsCode3.getLocationInWindow(location3);
                int[] location4 = {0, 0};
                tvSmsCode4.getLocationInWindow(location4);
                // 判断焦点位置坐标是否在空间内，如果位置在控件外，则隐藏键盘
                if ((event.getRawX() < left || event.getRawX() > right
                        || event.getY() < top || event.getRawY() > bootom)
                        && (event.getRawX() < location1[0] || event.getRawX() > location1[0] + view.getWidth()
                        || event.getY() < location1[1] || event.getRawY() > location1[1] + view.getHeight())
                        && (event.getRawX() < location2[0] || event.getRawX() > location2[0] + view.getWidth()
                        || event.getY() < location2[1] || event.getRawY() > location2[1] + view.getHeight())
                        && (event.getRawX() < location3[0] || event.getRawX() > location3[0] + view.getWidth()
                        || event.getY() < location3[1] || event.getRawY() > location3[1] + view.getHeight())
                        && (event.getRawX() < location4[0] || event.getRawX() > location4[0] + view.getWidth()
                        || event.getY() < location4[1] || event.getRawY() > location4[1] + view.getHeight())) {
                    // 隐藏键盘
                    hideKeyboard(view);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 友盟回调
        UmengClient.onActivityResult(this, requestCode, resultCode, data);
    }
}